<?php

class ProjectWuZiKuController extends Controller
{

	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id)
	{
		$this->render('view',array(
			'model'=>$this->loadModel($id),
		));
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate()
	{
		$model=new ProjectWuZiKu;

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['ProjectWuZiKu']))
		{
			$model->attributes=$_POST['ProjectWuZiKu'];
			if($model->save())
				$this->redirect(array('view','id'=>$model->id));
		}

		$this->render('create',array(
			'model'=>$model,
		));
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($id)
	{
		$model=$this->loadModel($id);

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['ProjectWuZiKu']))
		{
			$model->attributes=$_POST['ProjectWuZiKu'];
			if($model->save())
				$this->redirect(array('view','id'=>$model->id));
		}

		$this->render('update',array(
			'model'=>$model,
		));
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id)
	{
		$this->loadModel($id)->delete();

		// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
		if(!isset($_GET['ajax']))
			$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
	}

	/**
	 * Lists all models.
	 */
	public function actionIndex()
	{
		$dataProvider=new CActiveDataProvider('ProjectWuZiKu');
		$this->render('index',array(
			'dataProvider'=>$dataProvider,
		));
	}

	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
		$model=new ProjectWuZiKu('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['ProjectWuZiKu']))
			$model->attributes=$_GET['ProjectWuZiKu'];

		$this->render('admin',array(
			'model'=>$model,
		));
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer $id the ID of the model to be loaded
	 * @return ProjectWuZiKu the loaded model
	 * @throws CHttpException
	 */
	public function loadModel($id)
	{
		$model=ProjectWuZiKu::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param ProjectWuZiKu $model the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='project-wu-zi-ku-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
	
	
	/**
	 * action :上传项目物资excel
	 * 
	 * 设置session变量：
	 * Yii::app()->session['var']='value';
	 * 使用： echo Yii::app()->session['var'];
	 * 移除: unset(Yii::app()->session['var']);
	 */
	public function actionLoad()
	{
		$model = new Mobilefile;
		if(isset($_POST['Mobilefile'])){
			set_time_limit(1000);
			$model->attributes=$_POST['Mobilefile'];
			$file = CUploadedFile::getInstance($model, 'filePath');  
			if( is_object($file) && get_class($file) === 'CUploadedFile' ){  
				$extensionName = strtolower($file->getExtensionName());
				Yii::app()->session['Pwuzi_name'] = $_POST['Mobilefile']['version'];
				$modelName = get_class($model);
				$timestamp = time()-1320937220;//为了防止浏览器缓存，使用时间戳作为版本号(减去一个整数，可以减小版本号)
				$fileName = $modelName.'-'.$timestamp.'.'.$extensionName;
			    $model->filePath = $fileName;  
			}  
			$model->addTime = new CDbExpression('NOW()');
			if($model->validate()){
				if( $model->save() ){  
				    if(is_object($file) && get_class($file) === 'CUploadedFile'){  
				        $file->saveAs(Yii::app()->basePath.'/../uploads/'.$model->filePath);
				        Yii::app()->session['Pwuzi_url'] = Yii::app()->basePath.'/../uploads/'.$model->filePath;
				    }  
				 	$this->_Pwuzi(Yii::app()->session['Pwuzi_url']);//从excel导入mysql
				    $this->redirect(array('mobilefile/admin'));  
				}  
			}
		}
		
		exit("上传成功！");
		
	}
	
	/**
	 * 测试：actionUpExcel
	 */
	public function actionUpExcel()
	{
		$model = new Mobilefile;
		$this->render('upexcel',array(
			'model'=>$model,
		));
	}

	//action 插入ProjectWuziku表	
	public function _Pwuzi($path_url)
	{
		$sheetArray = Yii::app()->yexcel->readActiveSheet($path_url);
		
		foreach($sheetArray as $k=>$row)
		{
			if($k<4)
				continue;//不输出表头
			if($row['B']=="")
				continue;//uniqueId不能为空
			$modle = new ProjectWuZiKu;
			//$modle->id=$row['A'];
			//用session记录 projectId
			$modle->projectId = 1;
			Yii::app()->session['projectId'] = 1;
			$modle->wuZiId=$row['B'];
			$modle->name=$row['C'];
			$modle->pinyin = WuZiKu::model()->returnPinyin($row['C']);
			$modle->detail=$row['D'];
			$modle->measure=$row['E'];
			$modle->price=$row['G'];
			$modle->number=$row['F'];
			$modle->save(false);
		}
		$this->redirect(array('ProjectWuZiKu/selectwuzi'));
	}
	
	//select系统物资库
	public function actionSelectWuzi()
	{
		$criteria = new CDbCriteria;  
		$criteria->select = 'source'; //代表了要查询的字段，默认select='*' 
    	$criteria->group = 'source';  
		$wuziku = WuZiKu::model()->findAll($criteria);

		$this->render('selectwuzi',array(
			'wuziku'=>$wuziku,
		));
	}
	
	
	//项目 Compare 系统物资库
	public function actionCompare()
	{
		$_GET['source'] = isset($_GET['source'])?(string)$_GET['source']:'';
		$wuziku = WuZiKu::model()-> findAllByAttributes(array('source'=>$_GET['source'])); 
		$projectwuziku = ProjectWuZiKu::model()->findAllByAttributes(array('projectId'=>Yii::app()->session['projectId'],'wuZiKuId'=>"")); 
		
		$this->render('compare',array(
			'wuziku'=>$wuziku,
			'projectwuziku'=>$projectwuziku,
		));
	}
	
	//项目物资库 Compare 系统物资库
	public function actionCompareWuzi()
	{
		$wuziku = WuZiKu::model()->findAll();
		$projectwuziku = ProjectWuZiKu::model()->findAll();
		
		$this->render('comparewuzi',array(
			'wuziku'=>$wuziku,
			'projectwuziku'=>$projectwuziku,
		));
	}
	
	//Ajax 项目物资库 比对正确结果写入
	public function actionResultCompareRight()
	{
		$_POST['id'] = isset($_POST['id'])?(int)$_POST['id']:1;
		$ProjectWuZi = ProjectWuZiKu::model()->findByPk($_POST['id']);
		$wuZiKuId = substr($ProjectWuZi->wuZiId,-7);
		$ProjectWuZi->wuZiKuId = $wuZiKuId;
		$ProjectWuZi->save();
		echo "比对成功！";
	}
	
	//Ajax 项目物资库 比对错误结果写入
	public function actionResultCompareError()
	{
		$_POST['id'] = isset($_POST['id'])?(int)$_POST['id']:1;
		$ProjectWuZi = ProjectWuZiKu::model()->findByPk($_POST['id']);
		$ProjectWuZi->wuZiKuId = 'error';
		$ProjectWuZi->save();
		echo "Error！";
	}
	
	
	/**
	 * 根据项目ID获取该项目下的物资数据
	 */
	public function actionInteCompare()
	{	
		$pId = isset($_GET['projectId']) ? intval($_GET['projectId']) : 0;
		
		$projectWuZiKus = ProjectWuZiKu::model()->findAll(array('condition' => 'projectId = ' . $pId . ' and (wuZiKuId = \'\' or wuZiKuId = \'error\')'));
		
		if(!$projectWuZiKus)
			throw new CHttpException(404, 'Can\'t Find Data!');
		
		$this->render('inteCompare', array('projectWuZiKus' => $projectWuZiKus));
	}
	
	/**
	 * 智能修改某个物资
	 */
	public function actionInteSubmit()
	{
		$id = $_GET['id'];
		$wuZiKuIds = $_GET['wuZiKuIds'];
		
		$wuZiKuIds = str_replace(',', '|', $wuZiKuIds);
	
		$projectWuZiKu = ProjectWuZiKu::model()->findByPk($id);
		
		$projectWuZiKu->wuZiKuId = $wuZiKuIds;
		
		$projectWuZiKu->save();
		
		echo 1;
	}

}
